package com.oompu.cARd;

import java.io.IOException;

import com.metaio.sdk.MetaioDebug;
import com.metaio.tools.io.AssetsManager;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link LeftFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link LeftFragment#newInstance} factory method
 * to create an instance of this fragment.
 * 
 */
public class LeftFragment extends Fragment {

	WebView mWebView;

	/**
	 * Task that will extract all the assets
	 */
	AssetsExtracter mTask;
	
	/**
	 * Progress view
	 */
	View mProgress;

	/**
	 * True while launching a tutorial, used to prevent
	 * multiple launches of the tutorial
	 */
	boolean mLaunchingTutorial;
	
	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	private static final String ARG_PARAM1 = "param1";
	private static final String ARG_PARAM2 = "param2";

	// TODO: Rename and change types of parameters
	private String mParam1;
	private String mParam2;

	private OnLeftFragmentInteractionListener mListener;

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment LeftFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static LeftFragment newInstance(String param1, String param2) {
		LeftFragment fragment = new LeftFragment();
		Bundle args = new Bundle();
		args.putString(ARG_PARAM1, param1);
		args.putString(ARG_PARAM2, param2);
		fragment.setArguments(args);
		return fragment;
	}

	public LeftFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			mParam1 = getArguments().getString(ARG_PARAM1);
			mParam2 = getArguments().getString(ARG_PARAM2);
		}
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View frameView = inflater.inflate(R.layout.fragment_left, container, false);

		
		return frameView;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		// Enable metaio SDK log messages based on build configuration
		MetaioDebug.enableLogging(BuildConfig.DEBUG);
		 
		mProgress = getActivity().findViewById(R.id.progress);
		mWebView = (WebView) getActivity().findViewById(R.id.webview);
		
		// extract all the assets
		mTask = new AssetsExtracter();
		mTask.execute(0);
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnLeftFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	@Override
	public void onResume() 
	{
		super.onResume();
		mWebView.resumeTimers();
		mLaunchingTutorial = false;
	}
	
	@Override
	public void onPause() 
	{
		super.onPause();
		mWebView.pauseTimers();
	}

//	@Override
//	public void onBackPressed() 
//	{
//		// if web view can go back, go back
//		if (mWebView.canGoBack())
//			mWebView.goBack();
//		else
//			super.onBackPressed();
//	}
//	
	/**
	 * This task extracts all the assets to an external or internal location
	 * to make them accessible to metaio SDK
	 */
	private class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean>
	{

		@Override
		protected void onPreExecute() 
		{
			mProgress.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected Boolean doInBackground(Integer... params) 
		{
			try 
			{
				AssetsManager.extractAllAssets(getActivity().getApplicationContext(), true);
			} 
			catch (IOException e) 
			{
				MetaioDebug.printStackTrace(Log.ERROR, e);
				return false;
			}

			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) 
		{
			mProgress.setVisibility(View.GONE);
			
			if (result)
			{
				WebSettings settings = mWebView.getSettings();
				
		        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
				settings.setJavaScriptEnabled(true);
				
				mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
				mWebView.setWebViewClient(new WebViewHandler());
				mWebView.loadUrl("file:///android_asset/Menu/tutorial4.html");
				mWebView.setVisibility(View.VISIBLE);
			}
			else
			{
				MetaioDebug.log(Log.ERROR, "Error extracting assets, closing the application...");
				getActivity().finish();
			}
	    }
	}
	
	
	class WebViewHandler extends WebViewClient
	{
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) 
		{
			mProgress.setVisibility(View.VISIBLE);
		}
		
		@Override
		public void onPageFinished(WebView view, String url) 
		{
			mProgress.setVisibility(View.GONE);
		}
		
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String url) 
	    {
	    	if (!url.toLowerCase().startsWith("metaiosdkexample"))
	    	{
	    		if (url.contains("metaio.com"))
	    		{
	    			// Open external browser
	    			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
	    			intent.addCategory(Intent.CATEGORY_BROWSABLE);
	    			startActivity(intent);
	    			return true;
	    		}

	    		return false;
	    	}
	    	else if (mLaunchingTutorial)
	    	{
	    		return true;
	    	}
	    	
	    	
	    	final String tutorialId = url.substring(url.lastIndexOf("=") + 1);
	    	MetaioDebug.log("Tutorial ID detected: "+tutorialId);
	    	
	    	if (url.toLowerCase().startsWith("metaiosdkexample://"))
	    	{
	    		try 
	    		{
					final Class<?> activity = Class.forName(getActivity().getPackageName()+".Tutorial"+tutorialId);
					mLaunchingTutorial = true;
					startActivity(new Intent(getActivity().getApplicationContext(), activity));
				} 
	    		catch (ClassNotFoundException e) 
	    		{
					MetaioDebug.log(Log.ERROR, "Invalid tutorial id, class not found!");
				}
	    	}
	    	else if (url.toLowerCase().startsWith("metaiosdkexamplearel://"))
	    	{
	    		if (tutorialId != null)
	    		{
	    			final String arelConfigFile = "arelConfig"+tutorialId+".xml";
	    			final String arelConfigFilePath = AssetsManager.getAssetPath("Tutorial"+tutorialId+"/"+arelConfigFile);
	    			MetaioDebug.log("arelConfig to be passed to intent: "+arelConfigFilePath);
	    			Intent intent = new Intent(getActivity().getApplicationContext(), ARELViewActivity.class);
	    			intent.putExtra(getActivity().getPackageName()+".AREL_SCENE", arelConfigFilePath);
	    			mLaunchingTutorial = true;
	    			startActivity(intent);
	    		}
	    	}
	    	
	    	return true;
	    }
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnLeftFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}
	


}
